package com.example.myapplication.peripheral;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.nfc.NfcAdapter;
import android.util.Log;
import android.widget.Toast;

import com.st.st25sdk.NFCTag;
import com.st.st25sdk.STException;

public class UserNFC {
    private static final String TAG = "UserNFC";
    private static UserNFC INSTANCE;
    private Context context;
    private static short SMARTAG_END_ADDR_COMPACT_DATA   = 8192;
    private static short SMARTAG_BEGIN_ADDR_COMPACT_DATA = 120;
    public synchronized static UserNFC getInstance() {
        if (INSTANCE == null) {
            INSTANCE = new UserNFC();
        }
        return INSTANCE;
    }
    private NfcAdapter mNfcAdapter;
    private PendingIntent mPendingIntent;
    static private NFCTag mTag;
    /**
     * 初始化
     */
    public void init(Activity activity){
        context = activity;
        mNfcAdapter = NfcAdapter.getDefaultAdapter(context);
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S) {
            mPendingIntent = PendingIntent.getActivity(context, 0, new Intent(context, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), PendingIntent.FLAG_MUTABLE);
        } else {
            mPendingIntent = PendingIntent.getActivity(context, 0, new Intent(context, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), PendingIntent.FLAG_IMMUTABLE);
        }
    }
    public NFCTag getTag() {
        return mTag;
    }
    public void getNFC_DATA(){
        if(getTag() == null) {
            Toast.makeText(context, "No NFC Device", Toast.LENGTH_LONG).show();
        }
        else {
            Toast.makeText(context, "Reading NFC Data", Toast.LENGTH_LONG).show();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        byte[] byt = getTag().readBytes(SMARTAG_BEGIN_ADDR_COMPACT_DATA, SMARTAG_END_ADDR_COMPACT_DATA);
                        if (byt != null) {
                            Log.d("lzy", "length: " + byt.length);
                            Log.d("lzy", "data: " + DataUtils.bytes2Float(byt));
                            do_NFC_Data2(byt, byt.length);
                        }
                    } catch (STException e) {
                        //throw new RuntimeException(e);
                    }
                }
            }).start();
        }
    }
    private void do_NFC_Data2(byte[] data, int len)
    {

    }
}
